package com.iaiai.imail.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.iaiai.imail.core.IActivity;
import com.iaiai.imail.core.IServiceFactory;
import com.iaiai.imail.entity.Email;
import com.iaiai.imail.helper.MessageBox;

/**
 * 
 * <p>
 * Title: CreateActivity.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-9-12 上午11:49:05
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class CreateActivity extends IActivity {

	private EditText editText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.create);

		setTitleLayout(); // 设置头

		editText = (EditText) findViewById(R.id.email);
		if (getBundle().getString("email") != null) {
			editText.setText(getBundle().getString("email"));
		}

		setTitleText(getResources().getString(R.string.create_email_title));

		findViewById(R.id.next).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (editText.getText().toString().trim().length() <= 0) {
					editText.setError(getResources().getString(R.string.msg_create_null));
					return;
				}

				if (editText.getText().toString().trim().indexOf("@") <= 0) {
					editText.setError(getResources().getString(R.string.msg_create_email_error));
					return;
				}

				// 判断是否有此帐号的邮件
				Email email = IServiceFactory.getInstance().getEmailDao()
						.queryEmail(editText.getText().toString().trim());
				if (email != null) {
					MessageBox.showToast(CreateActivity.this, R.string.msg_create_repeat);
					return;
				}

				Intent activity = new Intent(CreateActivity.this, CreateInfoActivity.class);
				activity.putExtras(getAttribute());
				startActivity(activity);
				finish(); // 关闭当前
			}
		});
	}

	/**
	 * 设置头
	 */
	private void setTitleLayout() {
		if (getBundle().getBoolean("create")) {
			// 显示返回按钮
			insertTitleLayoutButton(R.drawable.icon_return, new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent activity = new Intent(CreateActivity.this, MainActivity.class);
					startActivity(activity);
					finish();
					overridePendingTransition(R.anim.push_down_out, R.anim.push_down_in);
				}
			});
		}
	}

	/**
	 * 存储数据
	 * 
	 * @return
	 */
	private Bundle getAttribute() {
		Bundle bundle = getBundle();
		bundle.putString("email", editText.getText().toString().trim());
		return bundle;
	}

}
